<?php
/*2017-4-10 15.45 jack*/
namespace app\api\model;
use plugin\filter;
use think\Db;
use think\Model;
use app\api;
use think\Session;

/*用户模型*/
class Users extends CommonModel
{
    public function __construct($args = [])
    {
        parent::__construct($args);
    }

    private $table_name = 'user';

    public function updateNickName($param)
    {
        $args = $this->default_param($param);
        $where = [];
        if(isset($param['client_id']))
        {
            $where['client_id'] = $param['client_id'];
        }
        if(isset($param['enc_client_id']))
        {
            $where['enc_client_id'] = $param['enc_client_id'];
        }
        if(empty($where))
        {
            return false;
        }

        db($this->table_name)->where($where)->update(['nickname'=>$args['nickname']]);

        return true;
    }

    /**登录接口
     * @param $args ['token','client_id'] 该参数可选。
     * @return array client_id,token
     */
    public function login($args = [])
    {
        $args = $this->default_param($args);

        //缺少参数，新增一个用户，并设置一个session
        if(empty($args['enc_client_id']) || empty($args['token']))
        {
            return $this->LoginSession($args);
        }
        //获取用户信息
        if(!($info = $this->user_info(['enc_client_id'=>$args['enc_client_id']]))) {
            return $this->LoginSession($args);}

        //检查token
        if($this->chkToken(array_merge(['token' => $args['token']],$info)))
        {
            //更新用户匿名
            if($args['nickname'] != $info['nickname'])
            {
                $this->updateNickName(['enc_client_id'=>$args['enc_client_id'],'nickname'=>$args['nickname']]);
            }

//            $this->clear_session();
            $token = $this->resetEncString(['client_id'=>$info['client_id'],'client_secrect'=>$info['client_secrect']]);

            //重新生成新秘钥
            return  [
                'client_id' => $info['client_id'],
                'enc_client_id'=> $this->EncUserid($info['client_id']),
                'user_name' => isset($args['user_name']) ? $args['user_name'] : "匿名",
                'nickname'  => $args['nickname'],
                'token'     => $token,
                'is_kf'     => $info['is_kf']
            ];
        }
        else
        {
            return $this->LoginSession($args);
        }
    }
    //检测登录
    public function chkLogin($args)
    {
        $args = $this->default_param($args);

        //缺少参数，新增一个用户，并设置一个session
        if(empty($args['enc_client_id']) || empty($args['token']))
        {
            return false;
        }
        //获取用户信息
        if(!($info = $this->user_info(['enc_client_id'=>$args['enc_client_id']]))) {
            return false;
        }

        //检查token
        if($this->chkToken(array_merge(['token' => $args['token']],$info)))
        {
            //重新生成新秘钥
            return  [
                'client_id' => $info['client_id'],
                'enc_client_id'=> $this->EncUserid($info['client_id']),
                'user_name' => isset($args['user_name']) ? $args['user_name'] : "匿名",
                'nickname'  => $args['nickname'],
                'token'     => $args['token'],
                'is_kf'     => $info['is_kf']
            ];
        }
        else
        {
            return  false;
        }
    }

    //新增一个用户，并设置session
    private function LoginSession($args){
//        $this->clear_session();
        $user = $this->add_user($args);
        $user['new_user'] = 1;
        return $user;
    }

    /** 登录成功后，重设enc_string
     * @param $args client_id,client_secrect
     * @return array client_id,token
     * @return array client_id,token
     */
    public function resetEncString($args)
    {
        $secrect = $this->getSecrect(['client_secrect'=>$args['client_secrect']]);
        $this->updateEncString(['client_id'=>$args['client_id'],'enc_string'=>$secrect['enc_string']]);

        return $secrect['token'];
    }


    /**
     * 新增一个用户
     * @param array $param ['kf_id']可传选项
     * @return client_id,加密后token
     */
    public function add_user($param = [])
    {
        $param = $this->default_param($param);
        cookie('kfip',$param['ip']);
        $args = $this->getSecrect();
        //插入基本信息
        $client_id =  db($this->table_name)->insertGetId([
            'client_secrect' => $args['client_secrect'],
            'enc_string'     => $args['enc_string'],
            'nickname'       => $param['nickname'],
            'kf_id'         => isset($param['kf_id']) ? $param['kf_id'] : 0,
            'ipcookie'            => $param['ipcookie'],
            'ip'            => $param['ip']
        ]);
        //更新加密的客户端id
        db($this->table_name)->where(['client_id'=>$client_id])->update(['enc_client_id'=>$this->EncUserid($client_id)]);

        return ['client_id'=>$client_id,'token'=>$args['token'],'nickname'=>'匿名','is_kf'=>0,'user_name'=>'匿名'];

    }

    /**获取用户名
     * @param array $args key:[client_id,kf_username,enc_client_id,ip], 中括号表示任选一个可以查询
     * @return bool
     */
    public function user_info($args = [])
    {
        if(empty($args)) return false;
        //参数合并
        $args = $this->default_param($args);
        //如果没有查询信息，返回空
        if(empty($args['client_id'] ) && empty($args['enc_client_id']) && empty($args['ip'])) return false;

        //根据client_id,kf_username,enc_client_id其中一个查询查
        if(!empty($args['client_id']))
        {
            $filter = ['u.client_id'=>$args['client_id']];
        }
        elseif(!empty($args['enc_client_id']))
        {
            $filter = ['u.enc_client_id'=>$args['enc_client_id']];
        }
        elseif(!empty($args['ip']))
        {
            $filter = ['u.ipcookie'=>$args['ip']];
        }
        //返回查询信息
        $user =  db($this->table_name)->alias('u')
            ->field('u.*,k.nickname kf_nickname,w.nickName')
            ->join('ecs_kf k','k.kf_id = u.kf_id','LEFT')
            ->join('ecs_wx_user w','w.user_id = u.client_id','LEFT')
            ->where($filter)->order('u.client_id DESC')->find();
        if(!empty($user))
        {
            $user['is_kf'] =  $user['kf_id'] > 0 ? 1 : 0;
            $user['nickname'] =
                !empty( trim($user['kf_nickname']) ) ? $user['kf_nickname']
                    : (!empty($user['nickName']) ? $user['nickName']
                       : (!empty($user['nickname']) ? $user['nickname'] : "匿名")
                );
        }
        return $user;
    }


    /**初始化参数
     * @param $args [client_id,token,enc_string,nickname]
     * @return array
     */
    private function default_param($args)
    {
        if(empty($args)) return;
        $find = [
            'client_id'       => "",
            "token"         => "",
            "enc_string"    => "",
            "nickname"      => "匿名",
            "kf_username"  => "",
            "kf_password"   => "",
            "ipcookie"            => empty(cookie('kfip')) && strlen(cookie('kfip')) != 40 ? sha1(real_ip().randString(15)) : cookie('kfip'),
            'ip'            => real_ip()
        ];
        $args = array_merge($find,$args);
        return $args;
    }

    /**生成一个加密token 并返回加密的信息细节
     * @param array $args [client_secrect] 如果传入client_secrect键，则表明只生成enc_string，而client_secrect则根据传入参数来定
     * @return array
     */
    private function getSecrect($args = [])
    {
        $enc_string = randString(15);
        $client_secrect = isset($args['client_secrect']) ? $args['client_secrect'] : randString(20);
        return [
            'enc_string' => $enc_string,
            'client_secrect' => $client_secrect,
            'token'     => $this->getToken(['enc_string'=>$enc_string,'client_secrect'=>$client_secrect])
        ];
    }

    /**检查一个token是否正确
     * @param $args [token,enc_string,client_secrect]
     * @return bool
     */
    public function chkToken($args)
    {
        return $args['token'] == $this->getToken(['enc_string'=>$args['enc_string'],'client_secrect'=>$args['client_secrect']]);
    }

    /**加密一个token
     * @param $args [enc_string,client_secrect] 根据这两个键值加密
     * @return string
     */
    public function getToken($args)
    {
        return md5($args['enc_string'].$args['client_secrect']);
    }

    /**更新一个用户的随机加密窜
     * @param $args [id,enc_string]
     */
    public function updateEncString($args)
    {
        db($this->table_name)->where(['client_id'=>$args['client_id']])->update(['enc_string'=>$args['enc_string']]);
    }



    public function getAllOnLineUser($OnLineArr = [])
    {
        //获取所有客服列表
        $kf_arr = db('user')->field('enc_client_id,nickname')->where(['kf_id'=>''])->limit(10)->select();
        //筛选所有客服是否在线

        return $this->setOnLineState($kf_arr,$OnLineArr);
    }



}